package cn.sgjk.train.business.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.sgjk.train.business.domain.*;
import cn.sgjk.train.business.enums.SeatColEnum;
import cn.sgjk.train.common.exception.BusinessException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import cn.sgjk.train.common.resp.PageResp;
import cn.sgjk.train.common.util.SnowUtil;
import cn.sgjk.train.business.mapper.DailyTrainCarriageMapper;
import cn.sgjk.train.business.req.DailyTrainCarriageQueryReq;
import cn.sgjk.train.business.req.DailyTrainCarriageSaveReq;
import cn.sgjk.train.business.resp.DailyTrainCarriageQueryResp;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

import static cn.sgjk.train.common.exception.BusinessExceptionEnum.BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR;

@Service
public class DailyTrainCarriageService {

    private static final Logger LOG = LoggerFactory.getLogger(DailyTrainCarriageService.class);

    @Resource
    private DailyTrainCarriageMapper dailyTrainCarriageMapper;

    @Autowired
    private TrainCarriageService trainCarriageService;

    public void save(DailyTrainCarriageSaveReq req) {
        DateTime now = DateTime.now();

        //自动计算出车座总数和列数
        List<SeatColEnum> seatColEnums = SeatColEnum.getColsByType(req.getSeatType());
        req.setColCount(seatColEnums.size());
        req.setSeatCount(seatColEnums.size() * req.getRowCount());


        DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(req, DailyTrainCarriage.class);
        //保存数据之前，先判断唯一键是否存在
        DailyTrainCarriage carriageDb = selectByUnique(req.getTrainCode(),req.getIndex());
        if (ObjectUtil.isNull(dailyTrainCarriage.getId())) {


            if(ObjectUtil.isNotEmpty(carriageDb)) {
                throw new BusinessException(BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
            }
            dailyTrainCarriage.setId(SnowUtil.getSnowflakeNextId());
            dailyTrainCarriage.setCreateTime(now);
            dailyTrainCarriage.setUpdateTime(now);
            dailyTrainCarriageMapper.insert(dailyTrainCarriage);
        } else {
            if(ObjectUtil.isNotEmpty(carriageDb)) {
                throw new BusinessException(BUSINESS_TRAIN_CARRIAGE_INDEX_UNIQUE_ERROR);
            }
            dailyTrainCarriage.setUpdateTime(now);
            dailyTrainCarriageMapper.updateByPrimaryKey(dailyTrainCarriage);
        }
    }

    public PageResp<DailyTrainCarriageQueryResp> queryList(DailyTrainCarriageQueryReq req) {
        DailyTrainCarriageExample dailyTrainCarriageExample = new DailyTrainCarriageExample();
        dailyTrainCarriageExample.setOrderByClause("date desc , train_code asc , `index` asc");
        DailyTrainCarriageExample.Criteria criteria = dailyTrainCarriageExample.createCriteria();

        if(ObjectUtil.isNotNull(req.getDate())) {
            criteria.andDateEqualTo(req.getDate());
        }

        if(ObjectUtil.isNotEmpty(req.getTrainCode())) {
            criteria.andTrainCodeEqualTo(req.getTrainCode());
        }

        LOG.info("查询页码：{}", req.getPage());
        LOG.info("每页条数：{}", req.getSize());
        PageHelper.startPage(req.getPage(), req.getSize());
        List<DailyTrainCarriage> dailyTrainCarriageList = dailyTrainCarriageMapper.selectByExample(dailyTrainCarriageExample);

        PageInfo<DailyTrainCarriage> pageInfo = new PageInfo<>(dailyTrainCarriageList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        List<DailyTrainCarriageQueryResp> list = BeanUtil.copyToList(dailyTrainCarriageList, DailyTrainCarriageQueryResp.class);

        PageResp<DailyTrainCarriageQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void delete(Long id) {
        dailyTrainCarriageMapper.deleteByPrimaryKey(id);
    }

    //唯一键是否存在抽取成一个方法
    private DailyTrainCarriage selectByUnique(String code, Integer index) {
        DailyTrainCarriageExample dailyTrainCarriage = new DailyTrainCarriageExample();
        dailyTrainCarriage.createCriteria().andTrainCodeEqualTo(code).andIndexEqualTo(index);
        List<DailyTrainCarriage> trainCarriage = dailyTrainCarriageMapper.selectByExample(dailyTrainCarriage);
        if(CollUtil.isEmpty(trainCarriage)) {
            return null;
        }else {
            return trainCarriage.get(0);
        }
    }

    public void genCarriage(Date date, String trainCode) {
        LOG.info("生成日期{}的车次车厢:{} 信息开始", DateUtil.formatDate(date),trainCode);

        //删除已有当天数据
        DailyTrainCarriageExample dailyTrainCarriageExample = new DailyTrainCarriageExample();
        dailyTrainCarriageExample.createCriteria()
                .andDateEqualTo(date).andTrainCodeEqualTo(trainCode);
        dailyTrainCarriageMapper.deleteByExample(dailyTrainCarriageExample);

        // 查出某车次全部车厢信息
        List<TrainCarriage> trainCarriages = trainCarriageService.selectAll(trainCode);
        if (CollUtil.isEmpty(trainCarriages)) {
            LOG.info("该车次没有车厢基础数据，生成该车次的车厢信息结束");
            return;
        }


        int trainSeatSum = trainCarriages.size();
        CountDownLatch downLatch = new CountDownLatch(trainSeatSum);

        for (TrainCarriage trainCarriage: trainCarriages) {

            LOG.info("开始生成{}车次车厢",trainCarriage.getTrainCode());
            new Thread(()->{
                long start = System.currentTimeMillis();

                DateTime now = new DateTime();
                DailyTrainCarriage dailyTrainCarriage = BeanUtil.copyProperties(trainCarriage, DailyTrainCarriage.class);
                dailyTrainCarriage.setId(SnowUtil.getSnowflakeNextId());
                dailyTrainCarriage.setDate(date);
                dailyTrainCarriage.setCreateTime(now);
                dailyTrainCarriage.setUpdateTime(now);
                dailyTrainCarriageMapper.insert(dailyTrainCarriage);

                long end = System.currentTimeMillis();
                downLatch.countDown();
                LOG.info("生成{}车次车厢完成,用时{}",trainCarriage.getTrainCode(),(end - start));
            }).start();
        }
        try {
            downLatch.await();
        } catch (InterruptedException e) {
            LOG.error("每日车次车厢生成失败",e);
        }
        LOG.info("生成日期{}的车次车厢:{} 信息结束", DateUtil.formatDate(date),trainCode);
    }

    public List<DailyTrainCarriage> selectBySeatType(Date date, String trainCode, String seatType) {
        DailyTrainCarriageExample example = new DailyTrainCarriageExample();
        example.createCriteria().andDateEqualTo(date)
                .andTrainCodeEqualTo(trainCode)
                .andSeatTypeEqualTo(seatType);

        return dailyTrainCarriageMapper.selectByExample(example);
    }
}
